--
-- Author: shineflag
-- Date: 2017-03-14 09:25:02
--
--  每隔一段时间将redis中需要保存的信息落地到db
local skynet = require "skynet"
local log = require "log"
local json = require("json")
local redis = require "skynet.db.redis"
local mysql = require "skynet.db.mysql"


local TAG = "MDATA_SAVE"
local GINFO_EXPIRE = 3600*24*7 --1星期的缓存时间 
local rdb     --redis数据库
local pokaa_db   --mysql数据库

local CMD = {}

local ginfo_id = {}


local function connect_pokaa_db()
	local function on_connect(db)
		db:query("set charset utf8");
		log.e(TAG, "pokaa db connected!")
	end

	local mconf = require("mysql_conf")

	log.e(TAG,"start connect mysql %s:%d",mconf.host, mconf.port)
	pokaa_db = mysql.connect({
		host = mconf.host,
		port = mconf.port,
		database = mconf.database,
		user = mconf.user,
		password = mconf.password,
		max_packet_size=1024*1024,
		on_connect=on_connect
		})

	if not pokaa_db then
		log.e(TAG,"failed to connect db")
		skynet.exit()
	end
end

local function redis_connect()
	local rconfs = require("redis_conf")
	local rport = rconfs["redis_mdata"]
	local rconf = rconfs[rport]
	local conf = {
		host = rconf.host,
		port = rconf.port,
		db = 0
	}
	log.e(TAG,"start connect redis %s:%d",conf.host, conf.port)
	rdb = redis.connect(conf)
end

--将redis 字符串数组 形式的结果转换成 table 形式
local function rdata2table(data)
	local t = {}
	for id = 1, #data, 2 do 
		t[data[id]] = data[id+1]
	end
	return t
end

--从redis中获取用户的所有游戏信息
local function getall_ginfo( mid )
	local gkey = string.format("ginfo_%d",mid)
	local ret  = rdb:hgetall(gkey)
	log.d(TAG,"ret[%s]",json.encode(ret))
	return rdata2table(ret)
end

--将data 更新到数据库
local function update_ginfo_db(mid,data)
	local sql = string.format("UPDATE pokaa_gameinfo SET money=%d, diamond=%d, score=%dWHERE mid=%d",
		data.money, data.diamond,data.score, mid)
	local res =  pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))
end

--
local function save_player_ginfo(mid)
	local data = getall_ginfo(mid)
	update_ginfo_db(mid,data)
end

--设置用户游戏数据在redis中的过期时间
local function expire_rinfo(mid)
	local key = "ginfo_" .. mid 
	rdb:expire(key, GINFO_EXPIRE)
end

--将redis中的数据落地到数据库中
local function save_ginfo(t)
	for  mid,_ in pairs(t) do 
		save_player_ginfo(mid)
		expire_rinfo(mid)
	end
end


--每隔一段时间更新数据
local function update()
	--log.d(TAG,"updata player num[%d]",#ginfo_id)
	local t = ginfo_id 
	ginfo_id = {} 
	save_ginfo(t)
end

--[[
	desc:有用户游戏信息改变
	param: id-用户的id
--]]

function CMD.ginfo(id)
	ginfo_id[id] = true
end



skynet.start(function ( ... )
	connect_pokaa_db()
	redis_connect()

	skynet.dispatch("lua", function( session,address, cmd,... )
		local f = CMD[cmd]
		if f then
			if session ~= 0 then
		   		skynet.ret(skynet.pack( f(...) ) )
		   	else
		   		f(...)
		   	end 
		else
		    log.e(TAG,string.format("address[%d] call not exist cmd[%s] ",address,cmd) )
	    end
	end)

	skynet.fork(function()
		while true do
			update()
			skynet.sleep(500)
		end
    end)
    
end)